﻿using com.kylin.sddemo.utils;
using ConsoleApp1.bestFitting;
using ConsoleApp1.controls.src;
using SDLib;
using SoundDesigner.Samples;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static SoundDesigner.Samples.ProductManager;

namespace ConsoleApp1
{
    public partial class Main : Form
    {
        

        private bool IsInit = true;

        public byte[] ManufacturerData;
        public Main()
        {
            InitializeComponent();
        }
        private void Main_Load(object sender, EventArgs e)
        {
            //输入输出频响曲线
            afrChart1.InitCurve(EnumCurveType.InputAndGain);
            afrChart2.InitCurve(EnumCurveType.InputAndOutput);
            //IO曲线
            aioChart1.InitCurve();
            FittingHelper.InitProductManager();
            FittingHelper.GetTargetCurveData();
        }
        private void Main_Shown(object sender, EventArgs e)
        {
            cmbProgrammer.SelectedIndex = 2;

            cmbCommunctionPort.Items.Clear();
            ArrayList list = new ArrayList();
            var SolutionTypeList = EnumUtils.EnumToList<CommunicationPort>();
            for (int i = 0; i < SolutionTypeList.Count; i++)
            {
                var item = SolutionTypeList[i];
                list.Add(new DictionaryEntry(item.Value, item.Name));
            }
            cmbCommunctionPort.DataSource = list;
            cmbCommunctionPort.DisplayMember = "Value";//显示出来的。Text
            cmbCommunctionPort.ValueMember = "Key";// value值。
            cmbCommunctionPort.SelectedValue = ((int)Constants.Port);

            cmbCurrentMemory.Items.Clear();
            list = new ArrayList();
            var parameterSpaceList = EnumUtils.EnumToList<ParameterSpace>();
            for (int i = 0; i < parameterSpaceList.Count; i++)
            {
                var item = parameterSpaceList[i];
                if (item.Value >= 0 && item.Value <= 7)
                {
                    list.Add(new DictionaryEntry(item.Value, item.Name));
                }
            }
            cmbCurrentMemory.DataSource = list;
            cmbCurrentMemory.DisplayMember = "Value";//显示出来的。Text
            cmbCurrentMemory.ValueMember = "Key";// value值。
            cmbCurrentMemory.SelectedValue = ((int)Constants.currentMemory);

            this.cmbProgrammer.DropDownStyle = ComboBoxStyle.DropDownList;
            this.cmbCommunctionPort.DropDownStyle =ComboBoxStyle.DropDownList;
            this.cmbCurrentMemory.DropDownStyle = ComboBoxStyle.DropDownList;
            IsInit = false;
        }


        private async void btnInitialize_Click(object sender, EventArgs e)
        {
            FittingHelper.productManager = new ProductManager();
            FittingHelper.LibraryInfo = "E7111V2" + ".library";
            FittingHelper.productManager.Initialize(FittingHelper.LibraryInfo, 0, productName: Constants.ProductName, programmer: Constants.Programmer);
            Console.WriteLine($"ProductManager is initialized");
            await FittingHelper.productManager.ConnectAsync(SDLib.CommunicationPort.kLeft);
            FittingHelper.deviceInfo = FittingHelper.productManager.GetConnectedDeviceInfo(SDLib.CommunicationPort.kLeft);
            Console.WriteLine(
            $"LibraryId                {FittingHelper.deviceInfo?.LibraryId}\n" +
            $"ProductId                {FittingHelper.deviceInfo?.ProductId}\n" +
            $"ChipId                   {FittingHelper.deviceInfo?.ChipId}\n" +
            $"ChipVersion              {FittingHelper.deviceInfo?.ChipVersion}\n" +
            $"HybridId                 {FittingHelper.deviceInfo?.HybridId}\n" +
            $"FirmwareId               {FittingHelper.deviceInfo?.FirmwareId}\n" +
            $"FirmwareVersion          {FittingHelper.deviceInfo?.FirmwareVersion}\n" +
            $"SerialId                 {FittingHelper.deviceInfo?.SerialId}\n" +
            $"IsValid                  {FittingHelper.deviceInfo?.IsValid}\n" +
            $"ParameterLockState       {FittingHelper.deviceInfo?.ParameterLockState}\n" +
            $"RadioApplicationVersion  {FittingHelper.deviceInfo?.RadioApplicationVersion}\n" +
            $"RadioBootloaderVersion   {FittingHelper.deviceInfo?.RadioBootloaderVersion}\n" +
            $"RadioSoftDeviceVersion   {FittingHelper.deviceInfo?.RadioSoftDeviceVersion}\n" +
            $"HybridSerial             {FittingHelper.deviceInfo?.HybridSerial}\n" +
            $"HybridRevision           {FittingHelper.deviceInfo?.HybridRevision}");
        }

        

        private  void Initialize_Click(object sender, EventArgs e)
        {
            FittingHelper.InitProductManager();
        }
        


        private void btnGetDeviceInfo_Click(object sender, EventArgs e)
        {
            FittingHelper.deviceInfo = FittingHelper.productManager.GetConnectedDeviceInfo(SDLib.CommunicationPort.kLeft);
            Console.WriteLine(
            $"LibraryId                {FittingHelper.deviceInfo?.LibraryId}\n" +
            $"ProductId                {FittingHelper.deviceInfo?.ProductId}\n" +
            $"ChipId                   {FittingHelper.deviceInfo?.ChipId}\n" +
            $"ChipVersion              {FittingHelper.deviceInfo?.ChipVersion}\n" +
            $"HybridId                 {FittingHelper.deviceInfo?.HybridId}\n" +
            $"FirmwareId               {FittingHelper.deviceInfo?.FirmwareId}\n" +
            $"FirmwareVersion          {FittingHelper.deviceInfo?.FirmwareVersion}\n" +
            $"SerialId                 {FittingHelper.deviceInfo?.SerialId}\n" +
            $"IsValid                  {FittingHelper.deviceInfo?.IsValid}\n" +
            $"ParameterLockState       {FittingHelper.deviceInfo?.ParameterLockState}\n" +
            $"RadioApplicationVersion  {FittingHelper.deviceInfo?.RadioApplicationVersion}\n" +
            $"RadioBootloaderVersion   {FittingHelper.deviceInfo?.RadioBootloaderVersion}\n" +
            $"RadioSoftDeviceVersion   {FittingHelper.deviceInfo?.RadioSoftDeviceVersion}\n" +
            $"HybridSerial             {FittingHelper.deviceInfo?.HybridSerial}\n" +
            $"HybridRevision           {FittingHelper.deviceInfo?.HybridRevision}");
        }

        private async void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                await FittingHelper.productManager.ConnectAsync(CommunicationPort.kLeft);
                Console.WriteLine($"Device is Connected");

                cmbProgrammer.Enabled = false;
                cmbCommunctionPort.Enabled = false;
            }
            catch (Exception error)
            {
                Console.WriteLine($"Error:{error.Message}");
            }
        }

        private void btnDisConnect_Click(object sender, EventArgs e)
        {
            try
            {
                FittingHelper.productManager.CloseProduct();
                cmbProgrammer.Enabled = true;
                cmbCommunctionPort.Enabled = true;
            }
            catch (Exception error)
            {
                Console.WriteLine($"Error:{error.Message}");
            }
        }

        private void btnReadActivityMemory_Click(object sender, EventArgs e)
        {
            _ = FittingHelper.productManager.ReadParametersAsync(CommunicationPort.kLeft, 0, ReadWriteMode.RAM);
        }

        private void btnRestoreformNVM_Click(object sender, EventArgs e)
        {
            _ = FittingHelper.productManager.ReadParametersAsync(CommunicationPort.kLeft, ((int)Constants.currentMemory), ReadWriteMode.NVM);
        }

        private void btnRestoreAllformNVM_Click(object sender, EventArgs e)
        {
            _ = FittingHelper.productManager.ReadParametersAsync(CommunicationPort.kLeft, 0, ReadWriteMode.NVM_ALL);
        }

        private void btnWriteActivityMemory_Click(object sender, EventArgs e)
        {
            _ = FittingHelper.productManager.WriteParametersAsync(CommunicationPort.kLeft, 0, ReadWriteMode.RAM);
        }

        private void btnBurntoNVM_Click(object sender, EventArgs e)
        {
            _ = FittingHelper.productManager.WriteParametersAsync(CommunicationPort.kLeft, ((int)Constants.currentMemory), ReadWriteMode.NVM);
        }

        private void btnWriteAllMemoryToNVM_Click(object sender, EventArgs e)
        {
            _ = FittingHelper.productManager.WriteParametersAsync(CommunicationPort.kLeft, 0, ReadWriteMode.NVM_ALL);
        }

        private void btnShowParam_Click(object sender, EventArgs e)
        {
            var MemoryIndex = (int)cmbCurrentMemory.SelectedValue;
            var parameters = FittingHelper.productManager.GetMemory(MemoryIndex).Parameters;
            foreach (var item in parameters)
            {
                var param = (IParameter)item;
                switch (param.Type)
                {
                    case ParameterType.kUnknownType:
                        break;
                    case ParameterType.kInteger:
                        Debug.WriteLine($"Name:{param.Name};ID:{param.Id};Value:{param.Value};");
                        break;
                    case ParameterType.kDouble:
                        Debug.WriteLine($"Name:{param.Name};ID:{param.Id};Value:{param.DoubleValue};");
                        break;
                    case ParameterType.kBoolean:
                        Debug.WriteLine($"Name:{param.Name};ID:{param.Id};Value:{param.BooleanValue};");
                        break;
                    case ParameterType.kIndexedList:
                        Debug.WriteLine($"Name:{param.Name};ID:{param.Id};Value:{param.Value};ListValues:{param.ListValues};");
                        break;
                    case ParameterType.kIndexedTextList:
                        Debug.WriteLine($"Name:{param.Name};ID:{param.Id};Value:{param.Value};ListValues:{param.TextListValues};");
                        break;
                    case ParameterType.kByte:
                        break;
                    default:
                        break;
                }

            }

        }

        private void btnShowSYStemParam_Click(object sender, EventArgs e)
        {
            var parameters = FittingHelper.productManager.Product.SystemMemory.Parameters;
            foreach (var item in parameters)
            {
                var param = (IParameter)item;
                switch (param.Type)
                {
                    case ParameterType.kUnknownType:
                        break;
                    case ParameterType.kInteger:
                        Debug.WriteLine($"Name:{param.Name};ID:{param.Id};Value:{param.Value};");
                        break;
                    case ParameterType.kDouble:
                        Debug.WriteLine($"Name:{param.Name};ID:{param.Id};Value:{param.DoubleValue};");
                        break;
                    case ParameterType.kBoolean:
                        Debug.WriteLine($"Name:{param.Name};ID:{param.Id};Value:{param.BooleanValue};");
                        break;
                    case ParameterType.kIndexedList:
                        Debug.WriteLine($"Name:{param.Name};ID:{param.Id};Value:{param.Value};ListValues:{param.ListValues};");
                        break;
                    case ParameterType.kIndexedTextList:
                        Debug.WriteLine($"Name:{param.Name};ID:{param.Id};Value:{param.Value};ListValues:{param.TextListValues};");
                        break;
                    case ParameterType.kByte:
                        break;
                    default:
                        break;
                }

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FittingHelper.productManager.ReadManufacturerData(CommunicationPort.kLeft,out ManufacturerData);
            for (int i = 0; i < ManufacturerData.Length; i++)
            {
                Console.WriteLine($" {i} ==> {ManufacturerData[i]:X2}");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ManufacturerData.Length; i++)
            {
                ManufacturerData[i] += 1;
                Console.WriteLine($" {i} ==> {ManufacturerData[i]}");
            }
            FittingHelper.productManager.WriteManufacturerData(CommunicationPort.kLeft, ManufacturerData);
        }

        private void cmbProgrammer_SelectedValueChanged(object sender, EventArgs e)
        {
            if (IsInit)
            {
                return;
            }
            Constants.Programmer = cmbProgrammer.SelectedText;
        }

        private void cmbCommunctionPort_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (IsInit)
            {
                return;
            }
            Constants.Port = (CommunicationPort)cmbCommunctionPort.SelectedValue;
        }

        private void cmbCurrentMemory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (IsInit)
            {
                return;
            }
            Constants.currentMemory = (ParameterSpace)cmbCurrentMemory.SelectedValue;
        }

        private void btnGetGraphData_Click(object sender, EventArgs e)
        {
            FittingHelper.GetCurveData();
            UpdateGraph();
        }

        private void UpdateGraph() {
            var ColorList = afrChart1.GetCurveColor();
            afrChart1.RemoveAllFrequencyGainCurves();
            afrChart1.SetCurveValue(FittingHelper.TargetInput);
            afrChart1.AddFrequencyGainCurve(FittingHelper.FrequencyList, FittingHelper.ArrDataList40, ColorList[0]);
            afrChart1.AddFrequencyGainCurve(FittingHelper.FrequencyList, FittingHelper.ArrDataList60, ColorList[1]);
            afrChart1.AddFrequencyGainCurve(FittingHelper.FrequencyList, FittingHelper.ArrDataList80, ColorList[2]);

            afrChart1.AddTargetCurve(FittingHelper.TargetFreqList, FittingHelper.TargetLowGain, ColorList[0]);
            afrChart1.AddTargetCurve(FittingHelper.TargetFreqList, FittingHelper.TargetMidGain, ColorList[1]);
            afrChart1.AddTargetCurve(FittingHelper.TargetFreqList, FittingHelper.TargetHighGain, ColorList[2]);

            afrChart1.RefreshChart();

            afrChart2.RemoveAllFrequencyGainCurves();
            afrChart2.SetCurveValue(FittingHelper.TargetInput);
            afrChart2.AddFrequencyGainCurve(FittingHelper.FrequencyOutList, FittingHelper.ArrDataCurveList40, ColorList[0]);
            afrChart2.AddFrequencyGainCurve(FittingHelper.FrequencyOutList, FittingHelper.ArrDataCurveList60, ColorList[1]);
            afrChart2.AddFrequencyGainCurve(FittingHelper.FrequencyOutList, FittingHelper.ArrDataCurveList80, ColorList[2]);

            afrChart2.AddTargetCurve(FittingHelper.TargetFreqList, FittingHelper.TargetLowOut, ColorList[0]);
            afrChart2.AddTargetCurve(FittingHelper.TargetFreqList, FittingHelper.TargetMidOut, ColorList[1]);
            afrChart2.AddTargetCurve(FittingHelper.TargetFreqList, FittingHelper.TargetHighOut, ColorList[2]);

            afrChart2.RefreshChart();

            ColorList = aioChart1.GetCurveColor();
            aioChart1.SetCurveValue(FittingHelper.InputList);
            aioChart1.RemoveAllIOCurve();
            aioChart1.AddIOCurve(FittingHelper.InputList, FittingHelper.ArrDataList200, ColorList[0]);
            aioChart1.AddIOCurve(FittingHelper.InputList, FittingHelper.ArrDataList1000, ColorList[1]);
            aioChart1.AddIOCurve(FittingHelper.InputList, FittingHelper.ArrDataList2000, ColorList[2]);
            aioChart1.AddIOCurve(FittingHelper.InputList, FittingHelper.ArrDataList4000, ColorList[3]);
            aioChart1.RefreshChart();
        }

        private void btnGetTargetData_Click(object sender, EventArgs e)
        {
            if (FittingHelper.productManager==null)
            {
                FittingHelper.InitProductManager();
            }
            FittingHelper.GetTargetCurveData();
            UpdateGraph();
        }
        

        private void btnBestFitting_Click(object sender, EventArgs e)
        {
            Autofit();
        }
        public  bool Autofit()
        {
            
           
            FittingHelper.Autofit();
            FittingHelper.GetCurveData();
            FittingHelper.GetCurveOutData();
            UpdateGraph();
            return true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            FittingHelper.Clear();
            FittingHelper.GetCurveData();
            FittingHelper.GetCurveOutData();
            UpdateGraph();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (FittingHelper.productManager == null)
            {
                FittingHelper.InitProductManager();
            }
            FittingHelper.InitFitting(0);
            FittingHelper.GetCurveData();
            FittingHelper.GetCurveOutData();
            UpdateGraph();
        }

        private async void btnGenerateTone_Click(object sender, EventArgs e)
        {
            await FittingHelper.productManager.GenerateTone(CommunicationPort.kLeft ,1000, 60,1000);
        }
        
    }
}
